package org.tio.http.common.session;

import java.io.Serializable;

import org.tio.utils.cache.ICache;

/**
 * 
 * @author tanyaowu 
 * 2017年8月5日 上午10:16:26
 */
public class HttpSessionManager implements java.io.Serializable {

	private static final long serialVersionUID = 6077020620501316538L;

	private ICache store = null;

	private static HttpSessionManager instance = null;

	/**
	 * @author tanyaowu
	 */
	private HttpSessionManager(ICache store) {
		this.store = store;
	}

	/**
	 * 
	 * @param store
	 * @return
	 * @author tanyaowu
	 */
	public static HttpSessionManager getInstance(ICache store) {
		if (instance == null) {
			synchronized (HttpSessionManager.class) {
				if (instance == null) {
					instance = new HttpSessionManager(store);
				}
			}
		}
		return instance;
	}
	
	/**
	 * 
	 * @param sessionId
	 * @return
	 * @author tanyaowu
	 */
	public HttpSession getHttpSession(String sessionId) {
		HttpSession httpSession = (HttpSession)store.get(sessionId);
		return httpSession;
	}

	/**
	 * 设置会话属性
	 * @param key
	 * @param value
	 * @author tanyaowu
	 */
	public void setAttribute(HttpSession httpSession, String key, Serializable value) {
		httpSession.setAttribute(key, value);
		store.put(httpSession.getId(), httpSession);
	}

	/**
	 * 获取会话属性
	 * @param key
	 * @return
	 * @author tanyaowu
	 */
	public Object getAttribute(HttpSession httpSession, String key) {
		return httpSession.getAttribute(key);
	}

	/**
	 * 
	 * @param key
	 * @author tanyaowu
	 */
	public void removeAttribute(HttpSession httpSession, String key) {
		httpSession.removeAttribute(key);
		store.put(httpSession.getId(), httpSession);
	}

	/**
	 * 清空所有属性
	 * 
	 * @author tanyaowu
	 */
	public void clear(HttpSession httpSession) {
		httpSession.clear();
		store.put(httpSession.getId(), httpSession);
	}
}
